﻿using System;
using GeoAPI.Geometries;
using YJKGridTopologyCal.Utilities;

namespace YJKGridTopologyCal.Index.Quadtree
{
	[Serializable]
	public class Root<T> : NodeBase<T>
	{
		public void Insert(Envelope itemEnv, T item)
		{
			int subnodeIndex = NodeBase<T>.GetSubnodeIndex(itemEnv, Root<T>.Origin.X, Root<T>.Origin.Y);
			if (subnodeIndex == -1)
			{
				base.Add(item);
				return;
			}
			Node<T> node = this.Subnode[subnodeIndex];
			if (node == null || !node.Envelope.Contains(itemEnv))
			{
				Node<T> node2 = Node<T>.CreateExpanded(node, itemEnv);
				this.Subnode[subnodeIndex] = node2;
			}
			Root<T>.InsertContained(this.Subnode[subnodeIndex], itemEnv, item);
		}

		private static void InsertContained(Node<T> tree, Envelope itemEnv, T item)
		{
			Assert.IsTrue(tree.Envelope.Contains(itemEnv));
			bool flag = IntervalSize.IsZeroWidth(itemEnv.MinX, itemEnv.MaxX);
			bool flag2 = IntervalSize.IsZeroWidth(itemEnv.MinY, itemEnv.MaxY);
			NodeBase<T> nodeBase;
			if (flag || flag2)
			{
				nodeBase = tree.Find(itemEnv);
			}
			else
			{
				nodeBase = tree.GetNode(itemEnv);
			}
			nodeBase.Add(item);
		}

		protected override bool IsSearchMatch(Envelope searchEnv)
		{
			return true;
		}

		private static readonly Coordinate Origin = new Coordinate(0.0, 0.0);
	}
}
